import streamlit as st
import math

st.title("全能数学计算器")

# 添加历史记录
def add_to_history(history_list, result):
    history_list.append(result)

# 查看历史记录
def show_history(history_list):
    if len(history_list) == 0:
        st.warning("暂无历史记录")
    else:
        st.write("历史记录：")
        for i, history in enumerate(history_list):
            st.write(f"{i+1}. {history}")

# 清除历史记录
def clear_history(history_list):
    history_list.clear()
    st.write("历史记录已清除")

# 基础四则运算
def basic_calculation(num1, operator, num2):
    result = None
    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "×":
        result = num1 * num2
    elif operator == "÷":
        result = num1 / num2
    return result

# 科学计数法及常见函数计算
def scientific_calculation(func, num):
    result = None
    if func == "√":
        result = math.sqrt(num)
    elif func == "sin":
        result = math.sin(num)
    elif func == "cos":
        result = math.cos(num)
    elif func == "tan":
        result = math.tan(num)
    elif func == "log":
        result = math.log10(num)
    elif func == "ln":
        result = math.log(num)
    elif func == "^2":
        result = num ** 2
    elif func == "^3":
        result = num ** 3
    elif func == "**":
        result = 10 ** num
    return result

# 计算器主程序
def calculator():
    st.write("请输入算式：")
    num1 = st.number_input("第一个数字：", value=0.0)
    operator = st.selectbox("选择运算符：", ["+", "-", "×", "÷"])
    num2 = st.number_input("第二个数字：", value=0.0)
    if st.button("计算（四则运算）", key="basic_calculation"):
        if operator == "÷" and num2 == 0:
            st.error("除数不能为0，请重新输入")
        else:
            result = basic_calculation(num1, operator, num2)
            if result != None:
                st.write(f"结果：{result}")
                add_to_history(history_list, f"{num1} {operator} {num2} = {result}")
    st.write("请输入函数：")
    func = st.selectbox("选择函数：", ["√", "sin", "cos", "tan", "log", "ln", "^2", "^3", "**"])
    num = st.number_input("输入数字：", value=0.0)
    if st.button("计算（科学计数法及常见函数）", key="scientific_calculation"):
        if func == "√" and num < 0:
            st.error("负数不能进行开方运算，请重新输入")
        else:
            result = scientific_calculation(func, num)
            if result != None:
                st.write(f"结果：{result}")
                add_to_history(history_list, f"{func}({num}) = {result}")

# 历史记录
history_list = []
if st.button("历史记录", key="show_history"):
    show_history(history_list)

# 清除历史记录
if st.button("清除历史记录", key="clear_history"):
    clear_history(history_list)

# 计算器
calculator()